/**
 * 创建信息Canvas元素
 * @param info 信息对象
 * @param valueKey 值键名
 * @param changeType 变化类型
 * @returns Promise<{canvas: HTMLCanvasElement, cleanup: () => void}>
 */

import primary from '../assets/image/primary.png'
import success from '../assets/image/success.png'
import warning from '../assets/image/warning.png'
import danger from '../assets/image/danger.png'
import primaryLabel from '../assets/image/primary_label.png'
import warningLabel from '../assets/image/warning_label.png'
import dangerLabel from '../assets/image/danger_label.png'


interface fontStyle {
  size?: string;
  family?: string;
  color?: string;
  width?: number;
  weight?:
    | number // 100-900
    | "normal" // 400
    | "bold" // 700
    | "bolder"
    | "lighter";
}

interface canvasOption {
  width?: number;
  height?: number;
  fontStyle?: fontStyle;
  labelStyle?: fontStyle
}

const imageUrlOption: any = {
    'primary': primary,
    'success': success,
    'warning': warning,
    'danger': danger,
    'primary_label': primaryLabel,
    'warning_label': warningLabel,
    'danger_label': dangerLabel,
}

const options = {
  width: 50,
  height: 75,
  fontStyle: {
    size: "24px",
    family: "HarmonyOS Sans SC",
    color: "#fff",
    weight: "bold",
  },
  labelStyle: {
    size: "16px",
    family: "HarmonyOS_Sans_SC_Medium",
    color: "#fff",
    weight: "normal",
  },
} as canvasOption;

export const createInfoCanvas = (
  info: any,
  valueKey?: string,
  changeType?: string
): Promise<{ canvas: HTMLCanvasElement; cleanup: () => void }> => {
  return new Promise((resolve, reject) => {
    // 创建canvas元素
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    if (!ctx) {
      reject(new Error("Could not get canvas context"));
      return;
    }

    // 设置canvas尺寸
    canvas.width = info?.width ?? options.width;
    canvas.height = info?.height ?? options.height;

    const icons = {
        icon: info.iconType ? imageUrlOption[info.iconType] : undefined,
        labelIcon: info.labelIconType ? imageUrlOption[info.labelIconType] : undefined
    }

    // 绘制背景
    const bgImageUrl = changeType
      ? icons.icon
      : icons?.[valueKey ? "icon" : "labelIcon"] ??
        (valueKey ? icons.icon : icons.labelIcon);
    const text = info?.[valueKey ?? "label"] || "";

    // 清理dom中的canvas
    const cleanup = () => {
      ctx.setTransform(1, 0, 0, 1, 0, 0); // 重置变换
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    };

    const valueFont = `
    ${info?.fontStyle?.weight ?? options?.fontStyle?.weight} 
    ${info?.fontStyle?.size ?? options?.fontStyle?.size}
    ${info?.fontStyle?.family ?? options?.fontStyle?.family}`;

    const labelFont = `
    ${info?.labelStyle?.weight ?? options?.labelStyle?.weight} 
    ${info?.labelStyle?.size ?? options?.labelStyle?.size}
    ${info?.labelStyle?.family ?? options?.labelStyle?.family}`;

    // 绘制文本
    const reloadText = (textOption: any) => {
      textOption.font = valueKey ? valueFont : labelFont;
      textOption.fillStyle =
        (valueKey ? info?.fontStyle?.color : info?.labelStyle?.color) ??
        options.fontStyle?.color;
      textOption.textBaseline = "middle";
      textOption.textAlign = "center";
      const textX = info?.textOffsetX ?? canvas.width / 2;
      const textY = info?.textOffsetY ?? canvas.height / 2 - 4;
      ctx.fillText(text, textX, textY);
    };

    if (bgImageUrl) {
      const image = new Image();
      image.crossOrigin = "Anonymous";
      image.onload = () => {
        canvas.width = info?.width ?? image.width;
        canvas.height = info?.height ?? image.height;

        // 重新获取context
        const reloadCtx = canvas.getContext("2d");
        if (!reloadCtx) {
          reject(new Error("Could not get canvas context after image load"));
          return;
        }

        // 绘制背景图片
        reloadCtx.drawImage(image, 0, 0);

        reloadText(reloadCtx);
        resolve({ canvas, cleanup });
      };

      image.onerror = () => {
        reject(new Error("Failed to load image"));
      };

      image.src = bgImageUrl;
    } else {
      reloadText(ctx);
      resolve({ canvas, cleanup });
    }
  });
};
